package v2ray

import (
	"context"
	"errors"
	"gitee.com/Luna-CY/hui-hui/internal/interface/application"
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"gitee.com/Luna-CY/hui-hui/internal/util/goroutine"
	"gitee.com/Luna-CY/hui-hui/server/http/response"
	"github.com/gin-gonic/gin"
)

func (cls *V2ray) Start(_ *gin.Context) (int, any, error) {
	logger.GetLogger().Sugar().Info("启动V2ray服务...")

	var state, _, _, _, _ = cls.v2ray.State()
	if application.Installed != state && application.Stopped != state && application.RunError != state {
		return response.InvalidRequest, nil, errors.New("启动失败，V2ray服务当前状态不可启动，请稍后再试")
	}

	var config = cls.v2ray.GetConfig()
	if 0 == len(config.Inbounds) || 0 == len(config.Outbounds) {
		return response.InvalidRequest, nil, errors.New("启动失败，V2ray配置无效，V2ray需要最少一条入站和出站协议，请前往配置管理更新配置后启动应用")
	}

	goroutine.Go(func() {
		if err := cls.v2ray.Start(context.Background(), true); nil != err {
			logger.GetLogger().Sugar().Errorf("启动V2ray服务失败: %s", err)
		}
	})

	return response.Ok, nil, nil
}
